package com.zhixing.common.converter;

import cn.hutool.core.util.StrUtil;
import com.zhixing.common.exception.ZhixingException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.lang.Nullable;
import java.lang.reflect.Field;
import static com.zhixing.common.domain.enums.HttpStatus.BAD_REQUEST;

public class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {
    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnum(targetType);
    }

    private static class StringToEnum<T extends Enum> implements Converter<String, T> {
        private final Class<T> enumType;

        StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Nullable
        public T convert(String source) {
            if (source.isEmpty()) return null;
            try {
                Field value = enumType.getDeclaredField("value");
                value.setAccessible(true);
                for (T enumConstant: enumType.getEnumConstants()) {
                    if (StrUtil.equals(source, value.get(enumConstant).toString()) ||
                            StrUtil.equals(source, enumConstant.toString())) return enumConstant;
                }
            } catch (Exception e) {
                throw new ZhixingException(BAD_REQUEST);
            }
            throw new ZhixingException(BAD_REQUEST);
        }
    }
}
